package BlockingQueue;


class MyBlockingQueue {
    //创建一个数组最大容量为1000
    private String[] data = new String[1000];
    private volatile int size = 0;
    private volatile int tail = 0;
    private volatile int head = 0;

    public void put(String elem) throws InterruptedException {
        synchronized(this) {
            while(size == data.length) {
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if(tail == data.length) {
                tail = 0;
            }
            this.notify();
            size++;
        }
    }
    public String get() throws InterruptedException {
        synchronized(this) {
            while(size == 0) {
                this.wait();
            }
            String ret = data[head];
            head++;
            //所有元素已经全部出队列
            if(head == data.length) {
                head = 0;
            }
            this.notify();
            size--;
            return ret;
        }
    }

}
public class demo1 {
    public static void main(String[] args){

        MyBlockingQueue queue = new MyBlockingQueue();

        //生产者
        Thread t1 = new Thread(() -> {
            int num = 1;
           while(true) {
               try {
                   queue.put(num + "");
                   System.out.println("生产元素：" + num);
                   num++;
                   //让生产者生产慢一些
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }

           }
        });

        //消费者
        Thread t2 = new Thread(() -> {
            while(true) {
                try {
                    String ret = queue.get();
                    System.out.println("消费元素：" + ret);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t2.start();
        t1.start();

    }
}
